package com.yamaikeji.web.controller.demo.controller;

import com.microsoft.cognitiveservices.speech.PropertyId;
import com.microsoft.cognitiveservices.speech.ResultReason;
import com.microsoft.cognitiveservices.speech.SpeechConfig;
import com.microsoft.cognitiveservices.speech.SpeechRecognizer;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;

import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Paths;

public class AudioToSrt {
    public static void main(String[] args) {
        String speechKey = "CmdpjcxYyxwr1OqxFilmX1y9YHCX6ToKesFUJUe2yXHLVJUuZuQTJQQJ99BCAC1i4TkXJ3w3AAAYACOGSRfA";
        String speechRegion = "centralus";
        String audioFilePath = "D:/output.wav";
        String srtFilePath = "D:/output.srt";

        try {
            // 配置语音识别
            SpeechConfig speechConfig = SpeechConfig.fromSubscription(speechKey, speechRegion);
            speechConfig.setProperty(PropertyId.SpeechServiceResponse_OutputFormatOption, "srt");
            speechConfig.setProperty(PropertyId.SpeechServiceResponse_RequestSentenceBoundary, "true");

            // 创建音频输入
            AudioConfig audioConfig = AudioConfig.fromWavFileInput(audioFilePath);
            SpeechRecognizer recognizer = new SpeechRecognizer(speechConfig, audioConfig);

            // 处理识别结果
            StringBuilder srtContent = new StringBuilder();
            // 在识别事件中使用
            recognizer.recognized.addEventListener((s, e) -> {
                System.out.println("识别结果: " + e.getResult().getText());
                System.out.println("识别结果: " + e.getResult().getOffset());
                System.out.println("识别结果: " + e.getResult().getDuration());
                if (e.getResult().getReason() == ResultReason.RecognizedSpeech) {
                    String startTime = formatTime(e.getResult().getOffset());
                    String endTime = formatTime(e.getResult().getOffset().add(e.getResult().getDuration()));
                    srtContent.append(String.format("%d\n%s --> %s\n%s\n\n",
                            srtContent.toString().split("\n\n").length + 1,
                            startTime, endTime,
                            e.getResult().getText()));
                }
            });

            // 开始识别
            recognizer.startContinuousRecognitionAsync().get();
            //System.out.println("识别中...按Enter键停止");
            //System.in.read();
            recognizer.stopContinuousRecognitionAsync().get();

            // 保存SRT文件
            Files.write(Paths.get(srtFilePath), srtContent.toString().getBytes());
            System.out.println("SRT字幕已保存至: " + srtFilePath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 将纳秒转换为SRT时间格式
    static String formatTime(BigInteger nanoseconds) {
        long totalMs = nanoseconds.divide(BigInteger.valueOf(1_000_000)).longValue(); // 纳秒→毫秒
        long hours = totalMs / 3_600_000;
        long minutes = (totalMs % 3_600_000) / 60_000;
        long seconds = (totalMs % 60_000) / 1_000;
        long milliseconds = totalMs % 1_000;
        return String.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, milliseconds);
    }
}